<!--
  @author:  long
  @date:    2023/5/31
  @file:    xx
  @require:
-->
<template>
  <div>
    <FixedOperation>
      <div class="flex items-center justify-between">
        <span>绩效申诉</span>
        <!-- 内容 -->
        <div class="text-right">
          <slot></slot>
          <el-button type="primary" plain @click="save" v-if="isCanStart"
            >提交</el-button
          >
          <el-button type="primary" @click="save">保存</el-button>

          <el-button type="danger" @click="close">关闭</el-button>
        </div>
      </div>
    </FixedOperation>
    <div class="appealForm app-container">
      <div class="px-20">
        <el-form
          label-width="100"
          :model="form"
          :rules="rules"
          ref="ruleFormRef"
        >
          <el-row :gutter="10">
            <el-col :span="6">
              <el-form-item label="申诉人：" required>
                {{ appealerNickName }}
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="职务：" required>
                {{ userInfo.job }}
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="岗位：" required>
                {{ userInfo.position }}
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="部门：" required>
                {{ userInfo.deptName }}
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="申诉事件：" prop="appealTitle">
                <el-input
                  placeholder="请输入申诉事件"
                  v-model="form.appealTitle"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="申诉理由：" prop="appealContent">
                <el-input
                  clearable
                  :rows="3"
                  type="textarea"
                  placeholder="请输入申诉事件"
                  v-model="form.appealContent"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="附件：">
                <el-upload
                  class="upload-demo"
                  action="#"
                  :before-upload="beforeAvatarUpload"
                  :http-request="
                    params => {
                      handleFileChange(params)
                    }
                  "
                  accept=".rar, .zip, .doc, .docx, .pdf,.png,.jpg,.jpeg"
                  :show-file-list="false"
                >
                  <el-button type="primary" style="font-size: 14px"
                    ><el-icon><UploadFilled /></el-icon>上传附件</el-button
                  >
                  <template #tip>
                    <div class="el-upload__tip">
                      支持格式：.rar, .zip, .doc, .docx, .pdf,.png,.jpg,.jpe
                      ，单个文件不能超过20MB
                    </div>
                  </template>
                </el-upload>
                <div class="text-14px mt-10px" style="width: 100%">
                  <div v-for="(item, index) in fileList" :key="item.fileId">
                    <a :href="item.url">{{ item.origFileName }}</a>
                    <el-button text plain @click="delFileName(index, 'file')"
                      >删除</el-button
                    >
                  </div>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div class="flex items-center justify-between mb-3">
        <TitleName
          title="关联绩效指标"
          icon="i-carbon-bookmark-filled"
        ></TitleName>
        <el-button plain type="primary" icon="Plus" @click="selectHandle"
          >选择考核指标</el-button
        >
      </div>
      <div class="selfAppealList">
        <el-table :data="selectTableData" border>
          <el-table-column
            type="index"
            label="序号"
            fixed="left"
            width="55"
            align="center"
          ></el-table-column>
          <el-table-column
            label="一级指标"
            fixed="left"
            prop="firstLevel"
            width="150"
          ></el-table-column>
          <el-table-column
            label="二级指标"
            fixed="left"
            prop="secondLevel"
            width="150"
          ></el-table-column>
          <el-table-column
            label="指标说明及工作内容、工作要求等"
            width="320"
            show-overflow-tooltip
            fixed="left"
            prop="content"
          ></el-table-column>
          <el-table-column label="指标单位" width="100" prop="unit">
          </el-table-column>
          <el-table-column
            label="指标值"
            width="100"
            prop="targetValue"
          ></el-table-column>
          <el-table-column
            label="考核评分标准"
            show-overflow-tooltip
            width="200"
            prop="scoreStandard"
          ></el-table-column>
          <el-table-column
            label="分值权重"
            width="100"
            prop="score"
          ></el-table-column>

          <el-table-column
            label="自评完成情况"
            width="130"
            prop="scoreDescriptionSelf"
          >
          </el-table-column>
          <el-table-column label="备注说明" width="130" prop="remark">
          </el-table-column>
          <el-table-column
            label="自评得分"
            align="center"
            fixed="right"
            prop="finalScoreSelf"
            width="80"
          >
          </el-table-column>
          <el-table-column
            fixed="right"
            label="考核得分"
            align="center"
            width="80"
            prop="finalScore"
          ></el-table-column>
        </el-table>
      </div>
      <el-dialog
        v-model="dialogVisible"
        class="appealDialog"
        fullscreen
        title="考核指标选择"
        @open="getAssessmentResult"
      >
        <!--     备选指标     -->
        <div class="mb-10">
          <div class="mb-5 flex items-center justify-between">
            <TitleName title="指标" icon="i-carbon-bookmark-filled"></TitleName>

            <el-row :gutter="10">
              <!--              <el-col :span="8" style="text-align: right">-->
              <!--                <el-button-->
              <!--                  v-if="multipleSelection.length > 0"-->
              <!--                  type="primary"-->
              <!--                  plain-->
              <!--                  >确认选中</el-button-->
              <!--                >-->
              <!--              </el-col>-->
              <el-col :span="12">
                <!--    年度        -->
                <el-date-picker
                  v-model="queryForm.year"
                  type="year"
                  format="YYYY"
                  class="year"
                  style="width: 100%"
                  :clearable="false"
                  value-format="YYYY"
                  placeholder="年份选择"
                  @change="handleSelectChange"
              /></el-col>
              <el-col :span="12">
                <!--     月份       -->
                <el-select
                  v-model="queryForm.month"
                  class="month"
                  popper-class="monthPopper"
                  placeholder="月份选择"
                  @change="handleSelectChange"
                >
                  <el-option
                    v-for="(item, i) in monthNames"
                    :key="i"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-col>
            </el-row>
          </div>
          <el-table
            height="32vh"
            v-loading="alternateLoading"
            :data="alternateTableData"
            border
            ref="alternateTableRef"
            row-key="id"
            reserve-selection
            @select="handleSelectionChange"
            @select-all="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column
              type="index"
              label="序号"
              fixed="left"
              width="55"
              align="center"
            ></el-table-column>
            <el-table-column
              label="一级指标"
              fixed="left"
              prop="firstLevel"
              width="150"
            ></el-table-column>
            <el-table-column
              label="二级指标"
              fixed="left"
              prop="secondLevel"
              width="150"
            ></el-table-column>
            <el-table-column
              label="指标说明及工作内容、工作要求等"
              width="320"
              fixed="left"
              prop="content"
              show-overflow-tooltip
            ></el-table-column>
            <el-table-column label="指标单位" width="100" prop="unit">
            </el-table-column>
            <el-table-column
              label="指标值"
              width="100"
              prop="targetValue"
            ></el-table-column>
            <el-table-column
              label="考核评分标准"
              width="200"
              show-overflow-tooltip
              prop="scoreStandard"
            ></el-table-column>
            <el-table-column
              label="分值权重"
              width="100"
              prop="score"
            ></el-table-column>

            <el-table-column
              label="自评完成情况"
              width="130"
              prop="scoreDescriptionSelf"
            >
            </el-table-column>
            <el-table-column label="备注说明" width="130" prop="remark">
            </el-table-column>
            <el-table-column
              label="自评得分"
              align="center"
              fixed="right"
              prop="finalScoreSelf"
              width="80"
            >
            </el-table-column>
            <el-table-column
              fixed="right"
              label="考核得分"
              align="center"
              width="80"
              prop="finalScore"
            ></el-table-column>
          </el-table>
        </div>

        <!--     已选指标     -->
        <div>
          <div>
            <TitleName
              title="已选指标"
              class="mb-5"
              icon="i-carbon-bookmark-filled"
            ></TitleName>
          </div>

          <el-table height="32vh" :data="selectTableData" border>
            <el-table-column
              type="index"
              label="序号"
              fixed="left"
              width="55"
              align="center"
            ></el-table-column>
            <el-table-column
              label="一级指标"
              fixed="left"
              prop="firstLevel"
              width="150"
            ></el-table-column>
            <el-table-column
              label="二级指标"
              fixed="left"
              prop="secondLevel"
              width="150"
            ></el-table-column>
            <el-table-column
              label="指标说明及工作内容、工作要求等"
              width="320"
              show-overflow-tooltip
              fixed="left"
              prop="content"
            ></el-table-column>
            <el-table-column label="指标单位" width="100" prop="unit">
            </el-table-column>
            <el-table-column
              label="指标值"
              width="100"
              prop="targetValue"
            ></el-table-column>
            <el-table-column
              label="考核评分标准"
              show-overflow-tooltip
              width="200"
              prop="scoreStandard"
            ></el-table-column>
            <el-table-column
              label="分值权重"
              width="100"
              prop="score"
            ></el-table-column>

            <el-table-column
              label="自评完成情况"
              width="130"
              prop="scoreDescriptionSelf"
            >
            </el-table-column>
            <el-table-column label="备注说明" width="130" prop="remark">
            </el-table-column>
            <el-table-column
              label="自评得分"
              align="center"
              fixed="right"
              prop="finalScoreSelf"
              width="80"
            >
            </el-table-column>
            <el-table-column
              fixed="right"
              label="考核得分"
              align="center"
              width="80"
              prop="finalScore"
            ></el-table-column>
            <el-table-column
              label="操作"
              fixed="right"
              align="center"
              width="80"
              type="primary"
            >
              <template #default="scope">
                <el-button link @click="delRow(scope.row)">移除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <template #footer>
          <el-button type="primary" @click="dialogConfirm">确认</el-button>
          <el-button @click="dialogClose">取消</el-button>
        </template>
      </el-dialog>
      <!-- 提交审批 -->
      <SubmissionProcess
        :dialog-param="examineParam"
        :flowOptions="flowOptions"
        @initiate="handleClose('initiate')"
        @close="handleClose('examine')"
      ></SubmissionProcess>
    </div>
  </div>
</template>

<script setup name="AppealForm">
import { getCurrentInstance } from 'vue'
import useUserStore from '@/store/modules/user'
import { delFile, uploadFile } from '@/api/salesManage/contractManage'
import useTagsViewStore from '@/store/modules/tagsView'
import { useRouter } from 'vue-router'
import SelfAppealList from '@/views/officeManage/performanceManage/performanceAppeal/modules/selfAppealList.vue'
const userStore = useUserStore()
const router = useRouter()
import { format } from 'date-fns'
import { getUserInfoByUserName } from '@/api/system/user'
import {
  editBizassessappealInfo,
  getAssessIndicatorsByAssessTime,
  getBizassessappealAppealinfo,
  saveBizassessappealInfo
} from '@/api/officeManage/appeal'
import { getBusinessProStatus, listProcess } from '@/api/workflow/process'
import SubmissionProcess from '@/businessComponents/SubmissionProcess/index.vue'
import { getDept, getListWithRole } from '@/api/system/dept'
const { proxy } = getCurrentInstance()

const data = reactive({
  queryForm: {
    year: format(new Date(new Date().getTime()), 'yyyy'),
    month: format(new Date(new Date().getTime()), 'MM')
  },
  form: {
    appealTitle: '',
    appealContent: ''
  },
  userInfo: {},
  rules: {
    appealTitle: [
      { required: true, message: '请输入申诉事件', trigger: 'blur' }
    ],
    appealContent: [
      { required: true, message: '请输入申诉理由', trigger: 'blur' }
    ]
  },
  monthNames: [
    { label: '一月', value: '01' },
    { label: '二月', value: '02' },
    { label: '三月', value: '03' },
    { label: '四月', value: '04' },
    { label: '五月', value: '05' },
    { label: '六月', value: '06' },
    { label: '七月', value: '07' },
    { label: '八月', value: '08' },
    { label: '九月', value: '09' },
    { label: '十月', value: '10' },
    { label: '十一月', value: '11' },
    { label: '十二月', value: '12' }
  ],
  fileList: [], // 上传文件列表
  alternateLoading: false
})
const {
  form,
  userInfo,
  rules,
  fileList,
  monthNames,
  queryForm,
  alternateLoading
} = toRefs(data)
const dialogVisible = ref(false) //弹窗开关
const alternateTableData = ref([]) //备选指标
const selectTableData = ref([]) //已选指标
const multipleSelection = ref([]) //多选数据
const appealId = ref('') //申诉id
const appealerNickName = ref('')

const examineParam = ref({}) //审批弹窗参数
const isExamine = ref(true) //流程是判断是否走审批按钮
const flowOptions = ref([]) //该业务的流程数据
const isCanStart = ref(true) // 判断该业务是否可以审批发起
const appointUserId = ref('')
const appointUserName = ref('')
watch(
  () => appealId.value,
  val => {
    if (val && !!location.href.match(/editAppeal/)) {
      examineParam.value.businessId = val
    } else if (
      (val && !!location.href.match(/detail/)) ||
      (val && !!location.href.match(/workDetail/))
    ) {
      // 待办详情-访问
      examineParam.value.businessId = val
      isExamine.value = false
    } else if (location.href.match(/addAppeal/)) {
      console.info('进入新增')
      // 走客户流程
      // initFlowFn('3')

      // isExamine.value = true
    }
  },
  {
    immediate: true
  }
)

// 绩效考核结果
const handleSelectChange = () => {
  getAssessmentResult()
}

/**
 * 弹窗结果确认
 */
const dialogConfirm = () => {
  dialogVisible.value = false
}

/**
 * 多选框确认
 * @param val
 */
const handleSelectionChange = (selection, row) => {
  selectTableData.value = [...selectTableData.value, ...selection]
  selectTableData.value = Array.from(
    new Set(selectTableData.value.map(item => item.id))
  ).map(id => {
    return selectTableData.value.find(item => item.id === id)
  })
  let index = selection.findIndex(item => item.id == row.id)
  //判断是否是取消选中，过滤掉取消选中的数据
  if (index == -1) {
    selectTableData.value = selectTableData.value.filter(
      item => item.id != row.id
    )
  }
}

/**
 * 移除已选指标
 */
const delRow = row => {
  proxy.$nextTick(() => {
    let obj = alternateTableData.value.find(item => {
      return row.id == item.id
    })
    proxy.$refs['alternateTableRef'].toggleRowSelection(obj, false)
  })
  selectTableData.value = selectTableData.value.filter(
    item => item.id !== row.id
  )
}

// 弹窗关闭
const dialogClose = () => {
  dialogVisible.value = false
}

/**
 * 获取申诉信息
 */
const getAppealInfoFn = () => {
  let id = appealId.value
  getBizassessappealAppealinfo(id).then(res => {
    form.value.appealTitle = res.data.appealTitle
    form.value.appealContent = res.data.appealContent
    //   考核人进入看到的指标信息与申诉人进入看到的指标信息使用字段不一致
    let arr = res.data.indicatorsList
    if (arr.length > 0) {
      arr.forEach(item => {
        let obj = res.data.appealIndicatorsList.find(
          t => t.indicatorsId == item.id
        )
        item.finalScoreSelf = obj.selfScore
        item.finalScore = obj.totalScore
      })
    }
    selectTableData.value = arr
    fileList.value = res.data.fileList
    appealerNickName.value = res.data.appealerNickName
    getUserInfo(res.data.appealerUserName)
  })
}

/**
 * 根据年月获取考核指标结果
 */
const getAssessmentResult = async () => {
  alternateLoading.value = true
  try {
    const res = await getAssessIndicatorsByAssessTime({
      assessAtYear: queryForm.value.year,
      assessAtMonth: queryForm.value.month,
      appraiseeId: userStore.user.userId
    })
    if (res.code === 200 && res.data) {
      alternateTableData.value = res.data
      proxy.$nextTick(() => {
        if (selectTableData.value.length > 0) {
          selectTableData.value.forEach(row => {
            let obj = alternateTableData.value.find(item => {
              return row.id == item.id
            })
            if (obj && obj != null) {
              proxy.$refs['alternateTableRef'].toggleRowSelection(obj, true)
            }
          })
        }
      })
    }
  } catch (error) {
    console.log(error)
    proxy.$modal.msgError(error)
  } finally {
    alternateLoading.value = false
  }
}

// 选择考核指标
const selectHandle = () => {
  dialogVisible.value = true
}

// 关闭
const handleClose = type => {
  switch (type) {
    case 'examine':
      //弹出框关闭
      examineParam.value.visible = false

      close()
      break
    case 'initiate':
      //审批 发起成功
      examineParam.value.visible = false
      close()
      break
  }
}

/**
 * 业务流程整体思路：
 * 1.查询该业务是否有流程
 * 2.根据该业务流程来判断
 * * 2.1没有流程-提示不能新建数据
 * * 2.2只有一条流程时，则不弹出框流程提交审核按钮隐藏，直接保存(得到返回的业务id) 现实下一环节人的显示及弹出框 -再发起
 * * 2.3多条流程时，点击保存(得到返回的业务id) ，再点击提交审核按钮，弹出框现实流程，直接保存(得到返回的业务id) 现实下一环节人的显示及弹出框 -再发起
 * @param {*} type  业务类型 项目是1 订单业务2 	客户模块业务3
 */
const initFlowFn = async type => {
  // 1.查询该业务是否有流程
  let comRes = await listProcess({
    pageNum: 1,
    pageSize: 9999,
    category: type
  })
  flowOptions.value = comRes.rows || []
  // 2.根据
  if (JSON.stringify(flowOptions.value) == '[]') {
    // 新建页面
    proxy.$modal.msgError('该业务没有流程，无法提交审批')
  } else if (flowOptions.value.length == 1) {
    //2.2 流程只有一个，只有一条流程时，则不弹出框流程提交审核按钮隐藏，直接点击保存
    // isExamine.value = true
    if (appealId.value != '' && appealId.value != null) {
      proxy.$nextTick(() => {
        handleExamine()
      })
    }
  } else {
    //2.3多条流程时
    handleExamine()
  }
}

/**
 * 提交审批 按钮
 */
const handleExamine = () => {
  if (!examineParam.value.businessId) {
    proxy.$modal.msgWarning('请重新发起审批')
    return false
  }
  console.info('我是审批')

  examineParam.value.businessName = form.value.appealTitle //项目名称

  examineParam.value.categoryCode = '25' //分类编码
  examineParam.value.appointUserId = appointUserId.value //考核人id
  examineParam.value.appointUserName = appointUserName.value //考核人名称

  examineParam.value.visible = true
  console.log('examineParam.value', examineParam.value)
}

/**
 * 保存
 */
const save = () => {
  proxy.$refs.ruleFormRef.validate((valid, fields) => {
    if (valid) {
      if (selectTableData.value.length == 0) {
        proxy.$modal.msgError('请选择需要申诉的考核指标')
        return
      }
      //   处理指标信息
      let detailList = selectTableData.value.map(item => {
        return {
          appraiseeId: userStore.user.userId,
          totalScore: item.finalScore,
          selfScore: item.finalScoreSelf,
          indicatorsId: item.id
        }
      })
      //   处理附件
      let fileName =
        fileList.value && fileList.value.length > 0
          ? fileList.value.map(item => {
              return item.fileName
            })
          : []
      let params = {
        appealContent: form.value.appealContent,
        appealTitle: form.value.appealTitle,
        appealerId: userStore.user.userId,
        appealerUserName: userStore.user.userName,
        detaillist: detailList,
        fileName: fileName
      }
      // 修改
      if (appealId.value != '') {
        params.id = appealId.value
        editBizassessappealInfo(params).then(res => {
          if (res.code === 200) {
            proxy.$modal.msgSuccess('修改成功')
            appointUserId.value = res.data.scoreList
              .map(item => item.assessorId)
              .join(',')
            appointUserName.value = res.data.scoreList
              .map(item => item.assessorName)
              .join(',')
            if (isCanStart.value) {
              getBusinessProStatusFn()
            }
          }
        })
      } else {
        //   新增+
        saveBizassessappealInfo(params).then(res => {
          if (res.code === 200) {
            proxy.$modal.msgSuccess('保存成功')
            appointUserId.value = res.data.scoreList
              .map(item => item.assessorId)
              .join(',')
            appointUserName.value = res.data.scoreList
              .map(item => item.assessorName)
              .join(',')
            appealId.value = res.data.id
            examineParam.value.businessId = res.data.id
            getBusinessProStatusFn()
          }
        })
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}

// 根据业务查询审批状态
const getBusinessProStatusFn = async () => {
  let statusRes = await getBusinessProStatus({ businessId: appealId.value })
  if (statusRes.data.canStart) {
    // canStart false时 不能发起，true则可以发起
    initFlowFn('25')
  } else {
    proxy.$modal.msgWarning('当前申诉，无法发起审批')
  }
}

/**
 * 返回
 */
const close = () => {
  useTagsViewStore().delView(router.currentRoute.value)
  router.go(-1)
}

/**文件上传 限制条件**/
function beforeAvatarUpload(rawFile) {
  if (rawFile.size / 1024 / 1024 > 20) {
    proxy.$modal.msgError('单个文件不能超过20MB!')
    return false
  }
}

// 上传附件
async function handleFileChange(params) {
  let formData = new FormData()
  formData.append('file', params.file)
  try {
    const res = await uploadFile(formData)
    if (res.code === 200 && res.data) {
      fileList.value.push(res.data)
      form.value.agentAgreementFileName = res.data.fileName
    }
  } catch (error) {
    console.log(error)
    proxy.$modal.msgError(error)
  }
}
// 删除文件
async function delFileName(index) {
  try {
    proxy.$modal.confirm('是否删除该文件').then(async () => {
      const file = fileList.value[index]
      const res = await delFile(file.fileName)
      if (res.code === 200) {
        form.value.agentAgreementFileName = ''
        fileList.value.splice(index, 1)
        proxy.$modal.msgSuccess(res.data)
      }
    })
  } catch (error) {
    console.log(error)
    proxy.$modal.msgError(error)
  }
}

/**
 * 获取用户信息
 */
const getUserInfo = userName => {
  // userInfo.value = userStore.user
  let userCode = userName || userStore.user.userName

  getUserInfoByUserName(userCode).then(res => {
    userInfo.value = res.data
    let params = {
      deptId: userInfo.value.deptId
    }
    getListWithRole(params).then(response => {
      userInfo.value.deptName = response.data[0].deptName
    })
  })
}

/**
 * 初始化
 */
const init = async () => {
  if (router.currentRoute.value.query.appealId) {
    appealId.value = router.currentRoute.value.query.appealId
    examineParam.value.businessId = router.currentRoute.value.query.appealId
    await getAppealInfoFn()
    let statusRes = await getBusinessProStatus({ businessId: appealId.value })
    if (!statusRes.data.canStart) {
      isCanStart.value = false
    }
  } else {
    appealerNickName.value = userStore.user.nickName
    //   获取用户信息
    await getUserInfo()
  }
}
init()
</script>

<style scoped lang="scss">
:deep(.monthPopper) {
  width: 300px !important;
}
.monthPopper .el-select-dropdown__item {
  width: 25%;
  display: inline-block;
  box-sizing: border-box;
  text-align: center;
  padding: 0;
}
::v-deep .appealDialog {
  .el-dialog__body {
    padding: 0 20px;
  }
}
</style>
